import time

from ..exception.TestException import TestException
from ..common.ui.PageElement import PageElement, POLL_FREQUENCY
from ..exception.errorcode import ErrorCode
from robot.api import logger


class AutoComplete(PageElement):

    def setValue(self, value):
        self.wait_element_presence()
        script = '$(arguments[0]).autocomplete(\'search\', \'{value}\')'.format(value=value)
        self._execute_script(script, self._get_web_element())
        try:
            self.check_value_exist(value)
            script = '$(\'.dropdown-list\').find(\'li[title="{value}"]\').click()'.format(value=value)
            self._execute_script(script, self._get_web_element())
        except Exception:
            logger.warn("There is no drop-down option. Use the fill method to set value!")
            self._get_web_element().send_keys(value)


    def check_value_exist(self, value, timeout=10, poll_frequency=POLL_FREQUENCY):
        script = 'return $(\'.dropdown-list\').find(\'li[title="{value}"]\').size()'.format(value=value)
        count = 0
        max_retry = timeout / poll_frequency
        while max_retry >= count:
            size = self._execute_script(script, self._get_web_element())
            if size == 0:
                count += 1
                time.sleep(0.5)
            else:
                break
        if max_retry < count:
            raise TestException.by_error_code(ErrorCode.AUTO_COMPLETE_NOT_VALUE, value=value)

    def get_identification(self):
        identification = {'class': ['form-control'],
                          'data-ui-role': ['autocomplete']
                          }
        return identification
